﻿namespace Vibstudio.NetConfigurator.UI
{
    #region Namespaces

    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Shapes;
    using System.Windows.Threading;

    #endregion

    public partial class LoadingWait : UserControl
    {
        #region Fields

        private readonly DispatcherTimer _animationTimer;

        #endregion

        #region Ctor(s)

        public LoadingWait()
        {
            InitializeComponent();

            _animationTimer = new DispatcherTimer(
                DispatcherPriority.ContextIdle, Dispatcher) { Interval = new TimeSpan(0, 0, 0, 0, 100) };
        }

        #endregion

        #region Methods

        private void HandleAnimationTick(object sender, EventArgs e)
        {
            SpinnerRotate.Angle = (SpinnerRotate.Angle + 36) % 360;
        }

        private void HandleLoaded(object sender, RoutedEventArgs e)
        {
            const double OFFSET = Math.PI;
            const double STEP = Math.PI * 2 / 10.0;

            SetPosition(C0, OFFSET, 0.0, STEP);
            SetPosition(C1, OFFSET, 1.0, STEP);
            SetPosition(C2, OFFSET, 2.0, STEP);
            SetPosition(C3, OFFSET, 3.0, STEP);
            SetPosition(C4, OFFSET, 4.0, STEP);
            SetPosition(C5, OFFSET, 5.0, STEP);
            SetPosition(C6, OFFSET, 6.0, STEP);
            SetPosition(C7, OFFSET, 7.0, STEP);
            SetPosition(C8, OFFSET, 8.0, STEP);
        }

        private void HandleUnloaded(object sender, RoutedEventArgs e)
        {
            Stop();
        }

        private void HandleVisibleChanged(object sender,
                                          DependencyPropertyChangedEventArgs e)
        {
            var isVisible = (bool)e.NewValue;
            if (isVisible)
            {
                Start();
            }
            else
            {
                Stop();
            }
        }

        private void SetPosition(Ellipse ellipse, double offset, double posOffSet, double step)
        {
            ellipse.SetValue(Canvas.LeftProperty, 50.0 + Math.Sin(offset + posOffSet * step) * 50.0);
            ellipse.SetValue(Canvas.TopProperty, 50 + Math.Cos(offset + posOffSet * step) * 50.0);
        }

        private void Start()
        {
            _animationTimer.Tick += HandleAnimationTick;
            _animationTimer.Start();
        }

        private void Stop()
        {
            _animationTimer.Stop();
            _animationTimer.Tick -= HandleAnimationTick;
        }

        #endregion
    }
}